from PyQt5 import QtCore, QtGui, QtWidgets
import sys
import ast
import pandas as pd
from PyQt5.QtWidgets import *
import importlib
from datetime import datetime
import socket
import cv2
import numpy as np
import os
import threading
import time
from ultralytics import YOLO
import queue

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../process")))
from process import Process


QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(798, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(20, 10, 101, 31))
        self.label.setObjectName("label")

        self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox.setGeometry(QtCore.QRect(20, 40, 281, 551))
        self.groupBox.setObjectName("groupBox")

        self.listWidget = QtWidgets.QListWidget(self.groupBox)
        self.listWidget.setGeometry(QtCore.QRect(10, 20, 261, 521))
        self.listWidget.setObjectName("listWidget")

        self.groupBox_2 = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox_2.setGeometry(QtCore.QRect(300, 40, 481, 301))
        self.groupBox_2.setObjectName("groupBox_2")

        self.tabWidget = QtWidgets.QTabWidget(self.groupBox_2)
        self.tabWidget.setGeometry(QtCore.QRect(10, 50, 461, 241))
        self.tabWidget.setObjectName("tabWidget")
        self.listWidget.itemDoubleClicked.connect(self.on_item_double_clicked)

        self.tab = QtWidgets.QWidget()
        self.tab.setObjectName("tab")

        # self.tableView = QtWidgets.QTableView(self.tab)
        # self.tableView.setGeometry(QtCore.QRect(10, 10, 441, 201))
        # self.tableView.setObjectName("tableView")

        self.tabWidget.addTab(self.tab, "")

        self.tab_2 = QtWidgets.QWidget()
        self.tab_2.setObjectName("tab_2")

        # self.tableView_2 = QtWidgets.QTableView(self.tab_2)
        # self.tableView_2.setGeometry(QtCore.QRect(10, 10, 441, 201))
        # self.tableView_2.setObjectName("tableView_2")
        self.tabWidget2 = QtWidgets.QTabWidget(self.tab_2)
        self.tabWidget2.setGeometry(QtCore.QRect(0, 0, 451, 211))
        self.tabWidget2.setObjectName("tabWidget")
        self.tab_s1 = QtWidgets.QWidget()
        self.tab_s1.setObjectName("Camera")
        self.tabWidget2.addTab(self.tab_s1, "Camera")


        self.tabWidget.addTab(self.tab_2, "")

        self.tab_4 = QtWidgets.QWidget()
        self.tab_4.setObjectName("tab_4")

        self.comboBox = QtWidgets.QComboBox(self.tab_4)
        self.comboBox.setGeometry(QtCore.QRect(70, 10, 291, 21))
        self.comboBox.setObjectName("comboBox")

        self.label_2 = QtWidgets.QLabel(self.tab_4)
        self.label_2.setGeometry(QtCore.QRect(10, 10, 54, 21))
        self.label_2.setObjectName("label_2")

        self.pushButton_3 = QtWidgets.QPushButton(self.tab_4)
        self.pushButton_3.setGeometry(QtCore.QRect(370, 10, 75, 23))
        self.pushButton_3.setObjectName("pushButton_3")
        self.pushButton_3.clicked.connect(self.collect)

        self.label_5 = QtWidgets.QLabel(self.tab_4)
        self.label_5.setGeometry(QtCore.QRect(10, 40, 54, 21))
        self.label_5.setObjectName("label_5")

        self.lineEdit_ = QtWidgets.QLineEdit(self.tab_4)
        self.lineEdit_.setGeometry(QtCore.QRect(70, 40, 101, 21))
        self.lineEdit_.setObjectName("lineEdit_")

        self.label_6 = QtWidgets.QLabel(self.tab_4)
        self.label_6.setGeometry(QtCore.QRect(170, 40, 41, 21))
        self.label_6.setObjectName("label_6")

        self.label_7 = QtWidgets.QLabel(self.tab_4)
        self.label_7.setGeometry(QtCore.QRect(210, 40, 54, 21))
        self.label_7.setObjectName("label_7")

        self.spinBox = QtWidgets.QSpinBox(self.tab_4)
        self.spinBox.setGeometry(QtCore.QRect(260, 40, 101, 22))
        self.spinBox.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.spinBox.setRange(0, 1000000)
        self.spinBox.setObjectName("spinBox")

        self.label_8 = QtWidgets.QLabel(self.tab_4)
        self.label_8.setGeometry(QtCore.QRect(360, 40, 21, 21))
        self.label_8.setObjectName("label_8")

        self.label_9 = QtWidgets.QLabel(self.tab_4)
        self.label_9.setGeometry(QtCore.QRect(10, 70, 101, 21))
        self.label_9.setObjectName("label_9")

        self.lineEdit = QtWidgets.QLineEdit(self.tab_4)
        self.lineEdit.setGeometry(QtCore.QRect(110, 70, 331, 20))
        self.lineEdit.setObjectName("lineEdit")

        self.groupBox_4 = QtWidgets.QGroupBox(self.tab_4)
        self.groupBox_4.setGeometry(QtCore.QRect(10, 90, 171, 121))
        self.groupBox_4.setObjectName("groupBox_4")

        self.listWidget2 = QtWidgets.QListWidget(self.groupBox_4)
        self.listWidget2.setGeometry(QtCore.QRect(10, 20, 151, 91))
        self.listWidget2.setObjectName("listWidget2")

        self.groupBox_5 = QtWidgets.QGroupBox(self.tab_4)
        self.groupBox_5.setGeometry(QtCore.QRect(180, 90, 271, 121))
        self.groupBox_5.setObjectName("groupBox_5")

        self.textBrowser_2 = QtWidgets.QTextBrowser(self.groupBox_5)
        self.textBrowser_2.setGeometry(QtCore.QRect(10, 20, 251, 91))
        self.textBrowser_2.setObjectName("textBrowser_2")

        self.tabWidget.addTab(self.tab_4, "")

        self.tab_3 = QtWidgets.QWidget()
        self.tab_3.setObjectName("tab_3")

        self.textBrowser_3 = QtWidgets.QTextBrowser(self.tab_3)
        self.textBrowser_3.setGeometry(QtCore.QRect(10, 10, 441, 201))
        self.textBrowser_3.setObjectName("textBrowser_3")

        self.tabWidget.addTab(self.tab_3, "")

        self.label_3 = QtWidgets.QLabel(self.groupBox_2)
        self.label_3.setGeometry(QtCore.QRect(20, 20, 54, 21))
        self.label_3.setObjectName("label_3")

        self.comboBox_2 = QtWidgets.QComboBox(self.groupBox_2)
        self.comboBox_2.setGeometry(QtCore.QRect(80, 20, 291, 21))
        self.comboBox_2.setObjectName("comboBox_2")

        self.pushButton = QtWidgets.QPushButton(self.groupBox_2)
        self.pushButton.setGeometry(QtCore.QRect(380, 20, 75, 21))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.clicked.connect(self.loaddata)

        self.label_3.raise_()
        self.comboBox_2.raise_()
        self.pushButton.raise_()
        self.tabWidget.raise_()

        self.groupBox_3 = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox_3.setGeometry(QtCore.QRect(300, 340, 481, 251))
        self.groupBox_3.setObjectName("groupBox_3")

        self.label_4 = QtWidgets.QLabel(self.groupBox_3)
        self.label_4.setGeometry(QtCore.QRect(10, 20, 54, 21))
        self.label_4.setObjectName("label_4")

        self.comboBox_3 = QtWidgets.QComboBox(self.groupBox_3)
        self.comboBox_3.setGeometry(QtCore.QRect(70, 20, 311, 21))
        self.comboBox_3.setObjectName("comboBox_3")

        self.pushButton_2 = QtWidgets.QPushButton(self.groupBox_3)
        self.pushButton_2.setGeometry(QtCore.QRect(390, 20, 75, 23))
        self.pushButton_2.setObjectName("pushButton_2")
        self.pushButton_2.clicked.connect(self.analyze)

        self.textBrowser = QtWidgets.QTextBrowser(self.groupBox_3)
        self.textBrowser.setGeometry(QtCore.QRect(10, 50, 461, 192))
        self.textBrowser.setObjectName("textBrowser")

        self.listWidget_sub2 = QtWidgets.QListWidget(self.tab)
        self.listWidget_sub2.setGeometry(QtCore.QRect(0, 0, 441, 201))
        self.listWidget_sub2.setObjectName("all")

        MainWindow.setCentralWidget(self.centralwidget)
        self.textBrowser_2.setLineWrapMode(QTextBrowser.NoWrap)

        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(3)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "<html><head/><body><p><span style=\" font-size:11pt; font-weight:600;\">数字化生态圈</span></p></body></html>"))
        self.groupBox.setTitle(_translate("MainWindow", "设备列表"))
        self.groupBox_2.setTitle(_translate("MainWindow", "统计"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "综合统计"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "设备统计"))
        self.label_2.setText(_translate("MainWindow", "模型选择:"))
        self.pushButton_3.setText(_translate("MainWindow", "开始采样"))
        self.label_5.setText(_translate("MainWindow", "采样时间"))
        self.label_6.setText(_translate("MainWindow", "min(s)"))
        self.label_7.setText(_translate("MainWindow", "采样频率"))
        self.label_8.setText(_translate("MainWindow", "张"))
        self.label_9.setText(_translate("MainWindow", "采样结果输出路径"))
        self.groupBox_4.setTitle(_translate("MainWindow", "采样指标"))
        self.groupBox_5.setTitle(_translate("MainWindow", "输出信息"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_4), _translate("MainWindow", "采样策略"))
        self.textBrowser_3.setHtml(_translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'SimSun\'; font-size:9pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">使用说明:</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">    采集的数据会保存在csv文件中,里面包含了具体设备采集的指标信息,模型识别信息,在数据选择中选择数据,点击数据读取就可以在[综合统计]和[设备统计]中查看综合数据和个别数据,在左侧设备列表可以查看当前设备连接信息情况</p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">    </p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">    [采样策略]中可以设定采样的方法,包括采样时间和频率,表明在点击开始采样后,各设备在这段时间内均匀时间间隔采样这么多张图片</p>\n"
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">    在读取了数据之后可以选择专家系统,通过点击专家系统把数据传入,可以得到专家系统对数据的分析输出结果</p>\n"
"<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><br /></p>\n"
"<p style=\"margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">    [注:]采样策略会自动保存在config.txt文件中</p></body></html>"))

        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("MainWindow", "使用说明"))
        self.label_3.setText(_translate("MainWindow", "数据选择:"))
        self.pushButton.setText(_translate("MainWindow", "数据读取"))
        self.groupBox_3.setTitle(_translate("MainWindow", "专家系统"))
        self.label_4.setText(_translate("MainWindow", "系统选择:"))
        self.pushButton_2.setText(_translate("MainWindow", "专家分析"))

        for i in index:
            item = QListWidgetItem(i)
            item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
            item.setCheckState(QtCore.Qt.Unchecked)
            self.listWidget2.addItem(item)

    def loaddata(self):
        global data
        data_path = data_dir+'/'+ui.comboBox_2.currentText()
        data = pd.read_csv(data_path)
        cam = data.columns[1:-1]
        ind = data.columns[0]
        all = data.columns[-1]
        self.tabWidget2.clear()
        for i in cam:
            self.tabt = QtWidgets.QWidget()
            self.tabt.setObjectName(i)
            self.tabWidget2.addTab(self.tabt, i)
            self.listWidget_sub = QtWidgets.QListWidget(self.tabt)
            self.listWidget_sub.setGeometry(QtCore.QRect(0, 0, 441, 181))
            self.listWidget_sub.setObjectName("listWidget"+i)
            for k, j in enumerate(data.loc[:, ind][:]):
                item = QListWidgetItem(j+'\t'+data.loc[k, i])
                self.listWidget_sub.addItem(item)
        self.listWidget_sub2.clear()
        for k, j in enumerate(data.loc[:, ind][:]):
            print(data.loc[k, all])
            item = QListWidgetItem(j + '\t' + str(data.loc[k, all]))
            self.listWidget_sub2.addItem(item)

    def collect(self):
        global refresh,result_queue
        refresh = False# 停止更新列表
        current_datetime = datetime.now()# 获取当前日期和时间
        model = self.comboBox.currentText()# 模型路径
        dur_time = float(self.lineEdit_.text())# 采集时间
        f = self.spinBox.value()# 采集张数
        dir= self.lineEdit.text()# 获取输出路径
        index_list=[]#用于存放勾选的要采集的指标
        camera_list=[]#用于存放勾选的设备ip
        for index in range(self.listWidget2.count()):
            item = self.listWidget2.item(index)
            if item.checkState() == QtCore.Qt.Checked:
                index_list.append(item.text())
        for index in range(self.listWidget.count()):
            item = self.listWidget.item(index)
            if item.checkState() == QtCore.Qt.Checked:
                camera_list.append(item.text())
        result_queue=queue.Queue()
        pro = Process(model)# 初始化处理程序
        list_ = [index_list,camera_list]
        ok = threading.Thread(target=get, args=(model, current_datetime, dur_time, f, index_list, dir))
        ok.start()
        img = threading.Thread(target=pro, args=(dur_time,list_, f,server_socket_img,result_queue))
        img.start()

        # res = result_queue.get()
        # res = pro(dur_time=dur_time, f=f, list_=[index_list,camera_list],client=server_socket_img) # 获得处理结果

    def analyze(self):
        global data
        file = "../expert/"+ui.comboBox_3.currentText().split('.')[0]+'.py'
        classname = ui.comboBox_3.currentText().split('.')[1]
        spec = importlib.util.spec_from_file_location("module.name", file)
        module = importlib.util.module_from_spec(spec)
        sys.modules["module.name"] = module
        spec.loader.exec_module(module)
        # 从模块中获取类
        expert = getattr(module, classname)(data)
        analysis_results, recommendations = expert.analyze()
        for analysis in analysis_results:
            self.textBrowser.append(analysis + "<br>")
            # print(analysis)
        for recommendation in recommendations:
            self.textBrowser.append(recommendation + "<br>")
            # print(recommendation)

    def on_item_double_clicked(self,item):
        vid = threading.Thread(target=video, args=(item,))
        vid.start()

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

def get(model,current_datetime,dur_time,f,index_list,dir):
    global refresh,result_queue
    while True:
        # print(result_queue)
        try:
            if not result_queue.empty():
                res = result_queue.get()
                name = model.split('.')[0] + '_' + '_'.join(str(current_datetime).split(':')[:-1])
                res.to_csv('.' + dir + '/' + name + '.csv', sep=',', index=False, encoding='utf-8',
                           header=0)  # 保存处理结果,命名规则是(模型名称_日期时间.csv)
                with open('../config.txt', 'w', encoding='utf-8') as file:  # 重写配置文件
                    file.write('dur_time:' + str(dur_time) + '\n')
                    file.write('f:' + str(f) + '\n')
                    file.write('dir:' + dir + '\n')
                    file.write('index:' + ','.join(index_list) + '\n')
                scan_data_file()  # 刷新数据文件
                print('collect over')
                res_tes = np.array(res)
                for i in res_tes:
                    ui.textBrowser_2.append('\t'.join(map(str, i)) + '<br>')  # 在输出框查看输出结果
                refresh = True
                break
        except queue.Empty:
            print("Timeout: No result received within the time limit.")
            break
        except Exception as e:
            print(f"Exception occurred: {e}")
            break

def video(item):
    global server_socket_img,refresh
    with refresh_lock:
        refresh = False
    # print(item.text())
    model = ui.comboBox.currentText()
    client,arrd = server_socket_img.accept()
    trained_model = YOLO("../model/" + model)  #
    if arrd[0] == item.text():
        window_name = "img:" + arrd[0]
        cv2.namedWindow(window_name, cv2.WINDOW_NORMAL)
        while True:
            try:
                length = recvall(client, 16)  # 接收数据长度
                if not length:
                    break
                string_data = recvall(client, int(length))
                data = np.frombuffer(string_data, dtype='uint8')
                frame = cv2.imdecode(data, cv2.IMREAD_COLOR)
                results = trained_model(frame)
                img = frame.copy()

                for result in results:
                    # 获取预测框
                    for box in result.boxes:
                        x1, y1, x2, y2 = box.xyxy[0].cpu().numpy().astype(int)
                        confidence = box.conf[0].cpu().numpy()
                        class_id = box.cls[0].cpu().numpy()
                        label = f'{trained_model.names[int(class_id)]} {confidence:.2f}'
                        # 绘制预测框
                        cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
                        cv2.putText(img, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
                cv2.imshow(window_name, img)
                if cv2.waitKey(1) & 0xFF == ord('q'):
                    cv2.destroyAllWindows(window_name)

                    break
            except Exception as e:
                print(f"Exception occurred: {e}")
                break
        with refresh_lock:
            refresh = True
def get_classes_from_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        file_content = file.read()

    # 解析Python源代码
    tree = ast.parse(file_content)

    # 提取类定义
    class_names = [node.name for node in ast.walk(tree) if isinstance(node, ast.ClassDef)]

    return class_names

def recvall(sock, count):
    buf = b''
    while count:
        newbuf = sock.recv(count)
        if not newbuf:
            return None
        buf += newbuf
        count -= len(newbuf)
    return buf
# 连接网络相机
def connect_camera():
    global server_socket_img,client_socket,clients
    ui.listWidget.clear()# 清除列表内容
    print(socket.gethostbyname(socket.gethostname()))
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# 创建通道
    server_socket.bind(("0.0.0.0", 5050))# 监听5050端口
    server_socket.listen(10)

    server_socket_img = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # 创建通道
    server_socket_img.bind(("0.0.0.0", 5051))  # 监听5050端口
    server_socket_img.listen(10)
    print("Server listening on port 5050...")
    while True:
        client_socket, client_address = server_socket.accept()# 接收到的套接字对象和客户端的地址
        print(f"New connection from {client_address}")
        clients.append((client_socket,client_address))#把接收到的信息保存起来
        print(f"Current connected clients: {[addr for _, addr in clients]}")
        client_handler = threading.Thread(target=handle_client, args=(client_socket, client_address))#另起一个线程运行handle_client
        client_handler.start()
        item = QListWidgetItem(client_address[0])
        item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
        item.setCheckState(QtCore.Qt.Checked)
        ui.listWidget.addItem(item)


def handle_client(client_socket, client_address):
    global refresh,clients
    disconnect = False
    while True:
        if not refresh:
            break
        try:
            length = recvall(client_socket, 16)
            if not length:
                disconnect = True
                break
            print(f"Received from {client_address}: {length.decode()}")
        except Exception as e:
            print(f"Exception occurred: {e}")
            break

    if disconnect and False:
        print(f"Client {client_address} disconnected")
        clients.remove((client_socket,client_address))
        client_socket.close()
        items = ui.listWidget.findItems(client_address[0], QtCore.Qt.MatchExactly)
        if items:
            for item in items:
                ui.listWidget.takeItem(ui.listWidget.row(item))
        print(f"Current connected clients: {[addr for _, addr in clients]}")

def scan_model_file():
    # 扫描读取模型文件
    pt_files = [f for f in os.listdir(model_dir) if f.endswith('.pt')]
    for i in pt_files:
        print("[scan model]:", i)
        ui.comboBox.addItem(i)

def scan_expert_file():
    # 读取全部的专家系统
    pt_files = [f for f in os.listdir(expert_dir) if f.endswith('.py')]
    for i in pt_files:
        file_path=expert_dir+"/"+i
        class_list = get_classes_from_file(file_path)
        for j in class_list:
            if 'expert' in j.split('_'):
                print("[scan expert]:", j)
                ui.comboBox_3.addItem(i.split('.')[0]+'.'+j)

def scan_data_file():
    ui.comboBox_2.clear()
    # 获取文件夹中所有CSV文件的文件名列表
    csv_files = [f for f in os.listdir(data_dir) if f.endswith('.csv')]
    for i in csv_files:
        print("[scan data]:",i)
        ui.comboBox_2.addItem(i)

def read_collcet_strategy():
    # 读取配置文件
    config={}
    if not os.path.exists('../config.txt'):
        ui.lineEdit_.setText(config['dur_time'])
        ui.spinBox.setValue(int(config['f']))
        ui.lineEdit.setText(config['dir'])
        ui.listWidget2.clear()
        check=[]
    else:
        with open('../config.txt', 'r',encoding='utf-8') as file:
            for line in file:
                a=line.strip().split(':')[0]
                b=line.strip().split(':')[1]
                config[a]=b
            ui.lineEdit_.setText(config['dur_time'])
            ui.spinBox.setValue(int(config['f']))
            ui.lineEdit.setText(config['dir'])
            ui.listWidget2.clear()
            check = config['index'].split(',')
    for i in index:
        item = QListWidgetItem(i)
        item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
        if i in check:
            item.setCheckState(QtCore.Qt.Checked)
            ui.listWidget2.addItem(item)
        else:
            item.setCheckState(QtCore.Qt.Unchecked)
            ui.listWidget2.addItem(item)

def main():
    scan_model_file()
    scan_expert_file()
    scan_data_file()
    connect = threading.Thread(target=connect_camera)
    connect.start()
    read_collcet_strategy()

if __name__ == "__main__":
    global data
    global refresh, server_socket_img
    refresh=True
    data = None
    # 初始化全局锁
    refresh_lock = threading.Lock()
    clients = []
    data_dir = '../data'
    model_dir = '../model'
    expert_dir = '../expert'
    process_dir = '../process'
    index=['溶解氧', 'pH值', '温度', '浊度', '总磷', '总氮', '水体透明度']
    app = QtWidgets.QApplication(sys.argv)
    mainWin = MainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(mainWin)
    main()
    mainWin.show()
    sys.exit(app.exec_())